package System;


import com.mysql.cj.jdbc.MysqlDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-02-03
 * Time: 01:34
 */
public class AddOperation implements IOperation {
    public void work() throws SQLException {
        System.out.println("新增图书！");
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入书名");
        String name = scanner.nextLine();
        System.out.println("请输入作者");
        String author = scanner.nextLine();
        System.out.println("请输入价格");
        int price = scanner.nextInt();
        scanner.nextLine();//读入回车
        System.out.println("请输入类型");
        String type = scanner.nextLine();

        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/BookControlSystem?characterEncoding=utf8&useSSL=False");
        dataSource.setUser("root");
        dataSource.setPassword("123456");

        Connection connection = dataSource.getConnection();

        String sql1 = "select * from BookList";
        PreparedStatement preparedStatement = connection.prepareStatement(sql1);
        ResultSet resultSet = preparedStatement.executeQuery();

        while (resultSet.next()){
            String name2 = resultSet.getString(1);
            if (name2.equals(name)){
                System.out.println("已存在这本书,无法添加");
                preparedStatement.close();
                connection.close();
                return;
            }
        }
        String sql2 = "insert into bookList values(?,?,?,?,?)";
        preparedStatement = connection.prepareStatement(sql2);
        preparedStatement.setString(1,name);
        preparedStatement.setString(2,author);
        preparedStatement.setInt(3,price);
        preparedStatement.setString(4,type);
        preparedStatement.setString(5,"未借出");

        preparedStatement.executeUpdate();
        System.out.println("《 "+ name+ " 》" +"添加成功");
        preparedStatement.close();
        connection.close();

    }
}
